AI.TreeIndex = Event.$extend({
  zTree:null,
  ds_metamodel:null,///菜单store
  menuData:[],
  setting: {
    async: {
        enable: false
        //,url: getUrlByNodeId
    },
    check: {
        enable: false
    },
    data: {
      key: {
        title: "title"//这里的s表示节点内的s属性
      }
    },
    edit: {
        enable: true,
        showRemoveBtn: false,
        showRenameBtn: false,
        drag: {
            isCopy: false,
            //暂时屏蔽拖拽方式移动
            isMove: false
            //  isCopy:true,
            //  isMove:true,
            //  prev:false,
            //  inner:true,
            //  next:false
        }
    },
    view: {
      showLine: false, showIcon: false, selectedMulti: false, dblClickExpand: false,
      addDiyDom: function(treeId, treeNode) {
        var spaceWidth = 5;
        var switchObj = $("#" + treeNode.tId + "_switch"),
        icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.before(switchObj);
        if (treeNode.level > 1) {
          var spaceStr = "<span style='display: inline-block;width:" + (spaceWidth * treeNode.level)+ "px'></span>";
          switchObj.before(spaceStr);
        }
      }
    },
    callback: {
    	onNodeCreated:function(event,treeId,treeNode){
       	 var span=$("#"+treeNode.tId+"_span");  
       	 if(treeNode.name!=undefined&&treeNode.name!=""){  
       	   span[0].title=treeNode.name;
       	 }  
         },
         onExpand:function(event,treeId,treeNode){
       	  if(treeNode.children.length>0){
       	    	for(var i=0;i<treeNode.children.length;i++){
       	    		var childTreeNode=treeNode.children[i];
       	    		var span=$("#"+childTreeNode.tId+"_span");  
       	    	    if(childTreeNode.name!=undefined&&childTreeNode.name!=""){  
       	    	      span[0].title=childTreeNode.name;
       	    	    } 
       	        }
       	    	$("#folderList li a span").attr('data-toggle','tooltip').attr('data-placement','right');
       	        $("[data-toggle='tooltip']").tooltip();
       	    }
         },
      onClick: function(event,treeId,treeNode){
    	  if(MainFram.treeClick){
    		  MainFram.treeClick(treeNode);
    	    	return false
    	  }
    	  else MainFram.treeIndex.treeNodeClick(event,treeId,treeNode);
      },
      beforeRightClick:function(treeId, treeNode){      
        zTree.selectNode(treeNode);
      },
      beforeExpand: function(treeId, treeNode){
       
      }, 
      onAsyncSuccess:function(event, treeId, treeNode, msg){//更新成功后调用
        if (msg.data.length == 0){
          zTree.removeChildNodes(treeNode);
          return;
        }
        if (typeof(successCallback) == 'function'){
          successCallback();
          successCallback = undefined;
        }
      },
      //新建文件夹、文件、重命名后回调（input blur时调用）
      onRename:function(event, treeId,treeNode){
        var parent = treeNode.getParentNode();
        //已存在检测
        if(zTree.getNodesByParam('name',treeNode.name,parent).length>1){
          core.tips.tips(LNG.name_isexists,false);
          zTree.removeNode(treeNode);
          return;
        }
        if (treeNode.create){//新建
          var path = treeNode.path+'/'+treeNode.name;       
          if (treeNode.type=='folder') {
            pathOperate.newFolder(path,function(data){
              if (!data.code) return;
              refresh(parent);
              successCallback = function(){
                var sel = zTree.getNodesByParam('name',treeNode.name,parent)[0];
                zTree.selectNode(sel);
                f5_refresh();
              }
            });           
          }else{//新建文件
             
          }
        }else{//重命名
          var from = treeNode.path + treeNode.beforeName;
          var to = treeNode.path + treeNode.name;
          var r = ds_metamodel.getRecordByKey(treeNode.id);
         
          r.set('MODELNAME', treeNode.name);
          ds_metamodel.commit();
          
        }
      }
    }
  },
  dealUrl:function(url,param){
    var keys = _.keys(param);
    for(var i=0;i<keys.length;i++){
      var key = keys[i];
      url = url.replace('{'+key+'}',param[key]);
    }
    return url;
  },
  loadModelTreeData:function(rootCode,data,showTitle){///从菜单里面加载
    showTitle = showTitle==false?showTitle:true;
    function getChildNodes(pNode){
      for(var i=0;i<ds_metamodel.getCount();i++){
          var r=ds_metamodel.getAt(i);
          if(r.get('PARENTCODE')!=pNode.id) continue;
          pNode.isParent=true;
          var node={title:r.get('REMARK')||r.get('MODELNAME'),id:r.get('MODELCODE'),name:r.get('MODELNAME'),url:r.get('URL'),nodeType:r.get('CLASSTYPE'),objtype:r.get('MODELTYPE'), isParent:false,children:[],filter:r.get('COUNTSQL')};
          pNode.children.push(node);
          getChildNodes(node);
        };
    };
    var metamodelSql="select modelcode,modelname,modeltype,parentcode,images ,classtype,remark,URL,COUNTSQL from metamodel where state = 'on'   "
    +" and (modelcode like '"+rootCode+"%' or parentcode='"+rootCode+"') and modelcode in (select modelcode  from METAPERMISSION where PERMISSIONLEVEL>='2' and groupcode in ( select a.groupcode from metagroupuser a,metagroup b where a.groupcode = b.groupcode and  username='" + _UserInfo.username + "'))"
    // +" and (modelcode like '"+rootCode+"%' or parentcode='"+rootCode+"')";
    +" order by seq";
    
    ds_metamodel = new AI.JsonStore({
        sql:metamodelSql,
        key:"MODELCODE",
        pageSize:-1,
        table:"METAMODEL"
    });


    for(var i=0;i<ds_metamodel.getCount();i++){
        var r=ds_metamodel.getAt(i);
        if(r.get('MODELCODE')==rootCode){
          MainFram.defaultFirstUrl=r.get('URL');
          if(showTitle) $("#treetitle").html(r.get('MODELNAME'));          
        };
        if(r.get('PARENTCODE')!=rootCode) continue;
        var node={title:r.get('REMARK')||r.get('MODELNAME'),id:r.get('MODELCODE'),name:r.get('MODELNAME'),objtype:r.get('MODELTYPE'),url:r.get('URL'),nodeType:r.get('CLASSTYPE'),isParent:false,children:[],filter:r.get('COUNTSQL')};
        if(!MainFram.defaultNodeId) MainFram.defaultNodeId=r.get('MODELCODE');
        data.push(node);  
        getChildNodes(node);
    };
  },
  treeNodeClick:function(event,treeId,treeNode){
    this.zTree.selectNode(treeNode);
    this.zTree.expandNode(treeNode);
    $("#folderList li a span").attr('data-toggle','tooltip').attr('data-placement','right');
    $("[data-toggle='tooltip']").tooltip();
    // console.log(treeNode);
    //var r = ds_metamodel.getRecordByKey(treeNode.id);
    var menuItemData = MainFram.treeIndex.getMenuItemData(treeNode.id);
    if(menuItemData && menuItemData.url && menuItemData.url.length>5){
    	console.log(menuItemData);
      $("#frame-right-main").hide();
      var _url= menuItemData.url;
      if(_url.indexOf("http://")>=0){
    	  _url = menuItemData.url;
      }
      else if(_url.indexOf("{contextPath}")>=0){
          _url=_url.replace('{contextPath}',contextPath);
      }
      else{ 
    	  _url="/"+contextPath+"/"+menuItemData.url;
      }
        
      var result = MainFram.explore.getTreeWhere(treeNode);
      if(_url.indexOf("?")!=-1){
        _url =_url+"&result="+result;
      }
      _url=_url.replace('{contextPath}',contextPath);
      _url = this.dealUrl(_url,{TEAMCODE:this.teamcode||''});
  
	  //ai.addTabSheet(treeNode.id,menuItemData.name,_url,true);
      $("#frame-right-iframe").attr("src",_url).show();
    }
    else  {
      $("#frame-right-iframe").attr("src","").hide();
      $("#frame-right-main").show();
    MainFram.explore.gotoPath(treeNode,menuItemData);
    }
  },
  getMenuItemData:function(menuId){
    var menuItemData=null;
    var getChildMenuItemData=function(childMenuDataArray){
      if(!childMenuDataArray) return;
      if(childMenuDataArray.length==0) return;
      for(var i=0;i<childMenuDataArray.length;i++){
        if(childMenuDataArray[i].id==menuId) {menuItemData=childMenuDataArray[i];break;}
        getChildMenuItemData(childMenuDataArray[i].children);
      }
    }
    for(var i=0;i<this.menuData.length;i++){
      if(this.menuData[i].id==menuId) {menuItemData=this.menuData[i];break;}
      getChildMenuItemData(this.menuData[i].children);
      if(menuItemData) break;
    };
    return menuItemData;
  },
  loadTreeData: function(options) {
    this.menuData=[];
    var loadMethod = options.loadMethod||'sync';
    var targetCode = options.targetCode||null;
    var containerId=options.containerId||"folderList";
    if(options.rootCode){
      this.loadModelTreeData(options.rootCode,this.menuData)
    }
    else{
      var menuSections=options.Sections;
      for(var i=0;i<menuSections.length;i++){
        var section=menuSections[i];
        if(section.id=='dbtopic') this.addDBTopic(this.menuData)
        //var node={id:section.id,name:section.name,objtype:'folder',children:[]};
        // if(section.id=='dataindex')this.buildDataIndex(this.menuData)
        //else if(section.id=='devindex')this.addMetaModelMenu(this.menuData)
        else if(section.id=='taskmgr')this.addTaskMgrMenu(this.menuData)
        else if(section.id=='problemMgr')this.addProblemMgrMenu(this.menuData)
        else if(section.id=='statemgr')this.addSimpleStateMenu(this.menuData); 
      };
    }
    $.fn.zTree.init($("#"+containerId), this.setting, this.menuData);
    this.zTree = $.fn.zTree.getZTreeObj(containerId);
    this.gotoPath(targetCode);
  },
  getRoot:function() {
    return this.zTree.getNodesByFilter(function (node) { return node.level == 0 }, true);
  },
  addTreeData:function(flatStore,rootCode,keyfield,namefield,urlfield,pkey,objtypefield,data,fileter){///通用的将数据变成树的格式
    if(!fileter) fileter="";
    var filterArray=fileter.split(",");
    function getChildNodes(pNode){
      for(var i=0;i<flatStore.getCount();i++){
          var r=flatStore.getAt(i);
          if(r.get(pkey)!=pNode.id) continue;
          
          var node={id:r.get(keyfield),name:r.get(namefield),url:r.get(urlfield),nodeType:"page",objtype:r.get(objtypefield), isParent:false,children:[]};
          getChildNodes(node);
          if(filterArray.length==0 || filterArray.indexOf(node.id)>=0)
          {  pNode.children.push(node); pNode.isParent=true;}
        };
    };
    for(var i=0;i<flatStore.getCount();i++){
        var r=flatStore.getAt(i);
        if(!r.get('PARENTCODE')) r.set('PARENTCODE','');
        if(!rootCode) rootCode="";
        if(r.get('PARENTCODE')!=rootCode) continue;
        var node={id:r.get(keyfield),name:r.get(namefield),objtype:r.get(objtypefield),url:r.get(urlfield),nodeType:"page",objtype:r.get(objtypefield),isParent:false,children:[]};
        
        getChildNodes(node);
        if(node.children.length>0 || filterArray.indexOf(node.id)>=0) data.push(node);  
    };
  },
  addTreeDataNoFileter:function(flatStore,rootCode,keyfield,namefield,urlfield,pkey,objtypefield,data){///通用的将数据变成树的格式
    function getChildNodes(pNode){
      for(var i=0;i<flatStore.getCount();i++){
          var r=flatStore.getAt(i);
          if(r.get(pkey)!=pNode.id) continue;
          
          var node={id:r.get(keyfield),name:r.get(namefield),url:r.get(urlfield),fieldname:r.get('RULETYPE'),objtype:'TOPIC', isParent:false,children:[]};
           pNode.children.push(node); pNode.isParent=true;
          getChildNodes(node);
        };
    };
    for(var i=0;i<flatStore.getCount();i++){
        var r=flatStore.getAt(i);
        if(!r.get('PARENTCODE')) r.set('PARENTCODE','');
        if(!rootCode) rootCode="";
        if(r.get('PARENTCODE')!=rootCode) continue;
        var node={id:r.get(keyfield),name:r.get(namefield),objtype:r.get(objtypefield),url:r.get(urlfield),fieldname:r.get('RULETYPE'),isParent:false,children:[]};
        getChildNodes(node);
        data.push(node);  
    }
  },
  addDBMetaModelMenu:function(data){///按库-元模型加载
    var dbArray=['仓库','Hadoop','指标库','前台应用库','接口采集平台'];
    var metamodelSql = "select OBJCODE,PARENTCODE,OBJNAME from metaobjmodel order by ORDSEQ  ";
    ds_metamodel = new AI.JsonStore({
        sql: metamodelSql ,
        key: "OBJCODE",
        pageSize: -1,
        table: "METAMODEL"
    });
    for(var idb=0;idb<dbArray.length;idb++){
           var node = {  id: dbArray[idb], name: dbArray[idb],  iconSkin:"my",    isParent: true, children: [] };
           for (var i = 0; i < ds_metamodel.getCount(); i++) {
            var r = ds_metamodel.getAt(i);
        
           if (r.get('PARENTCODE') !="META" ) continue;
        
            var cnode = {  id: r.get('OBJCODE'), name: r.get('OBJNAME'),  iconSkin:"my",    isParent: false, children: [] };
            node.children.push(cnode);
         
        };
          data.push(node);
   };
  },
   
  addDBTopic:function(data){
    
    var dbArray=ai.getStoreData("select dbname,cnname from metadb_list order by ordseq");
    
    for(var i=0;i<dbArray.length;i++){
      var db=dbArray[i];
      var node={id:db.DBNAME,name:db.CNNAME,fieldname:'dbname',objtype:'DATABASE',children:[]};
      var dbTopicStore= new AI.JsonStore({
        sql: "select DBNAME,RULECODE,PARENTCODE,RULETYPE,RULENAME from metadb_struct where dbname='"+db.DBNAME+"'" ,
        key: "RULECODE",
        pageSize: -1,
        table: "PARENTCODE"
     });
     this.addTreeDataNoFileter(dbTopicStore,"","RULECODE","RULENAME","","PARENTCODE","RULETYPE",node.children)  
     data.push(node);
    }
  },
  /*
  addSimpleStateMenu:function(data){///简单的状态管理
    var node = {
      id: 'devstate',  name:'统计分析', nodetype:'state',  isParent: true,
      children: [
         { id: 'new',  name:'总统情况',  filter:"state='新建'",  isParent: false},
         { id: 'chg',  name:'历史趋势', filter:"state='编辑'",  isParent: false},
         { id: 'test',  name:'问题情况',  filter:"state='test'",  isParent: false}
      ]
    };
    data.push(node);
  },
  addProglomMenu:function(data){///问题稽核管理
    var node = {
      id: 'devstate',  name:'问题管理', nodetype:'state',  isParent: true,
      children: [
         { id: 'new',  name:'未纳入主题',  filter:"state='新建'",  isParent: false},
         { id: 'chg',  name:'元数据不完整', filter:"state='编辑'",  isParent: false},
         { id: 'test',  name:'规范检查有问题',  filter:"state='test'",  isParent: false},
         { id: 'upline',  name:'未受控的表',  filter:"state='upline'",  isParent: false},
         { id: 'dim',  name:'维度表不规范',  filter:"state='upline'",  isParent: false}
      ]
    };
    data.push(node);
  },
  addTaskMgrMenu:function(data){///开发任务管理
    var node = {
      id: 'devtask',  name:'任务管理',  isParent: true,
      children: [
         { id: 'my-task',  url:'ftl/me/wfmgr/WFTaskList?type=my&teamCode='+this.teamcode,  name:'我的任务单',   isParent: false},
         { id: 'wait-task', url:'ftl/me/wfmgr/WFTaskList?type=wait&teamCode='+this.teamcode,   name:'待办任务单',  iconSkin:"my",  isParent: false},
         { id: 'query-task',  url:'ftl/me/wfmgr/WFTaskList?teamCode='+this.teamcode,  name:'任务单查询',  iconSkin:"my",  isParent: false}
         // ,{ id: 'new-task', url:'/me/mteam/tabmain.html', name:'数据申请审批',  iconSkin:"my",  isParent: false},
         
      ]
    };
    data.push(node);
  },
  addProblemMgrMenu:function(data){///问题管理
    var node = {
      id: 'problemMgr',  name:'问题管理',  isParent: true,
      children: [
         { id: 'my-problem',  url:'ftl/me/wfquestion/WFQuestionList?type=my&teamCode='+this.teamcode,  name:'我的问题',   isParent: false},
         { id: 'wait-problem', url:'ftl/me/wfquestion/WFQuestionList?type=wait&teamCode='+this.teamcode,   name:'待办问题',  iconSkin:"my",  isParent: false},
         { id: 'query-problem',  url:'ftl/me/wfquestion/WFQuestionList?teamCode='+this.teamcode,  name:'问题查询',  iconSkin:"my",  isParent: false},
         // { id: 'new-task', url:'/me/mteam/tabmain.html', name:'数据申请审批',  iconSkin:"my",  isParent: false},
         
      ]
    };
    data.push(node);
  },
  addPlatFormMonitorMenu:function(data){///平台监控
    var node = {
      id: 'platFormMonitor',  name:'平台监控',  isParent: true,
      children: [
         // { id: 'dataMonitor',  url:'ftl/task/dataMonitor?TEAM_CODE='+this.teamcode,  name:'数据监控',   isParent: false},
         { id: 'taskMonitor', url:'task/taskMonitor?TEAM_CODE='+this.teamcode,   name:'任务监控',  iconSkin:"my",  isParent: false}
         // { id: 'disMonitor', url:'daas/distribute/dis_monitor?TEAM_CODE='+this.teamcode,   name:'分发监控',  iconSkin:"my",  isParent: false}
      ]
    };
    data.push(node);
  },
  */
  initTree: function(options) {
    if(this.zTree) zTree.destroy(); 
    this.loadTreeData(options);
    this.buildTreeContextMenu();
  },
  buildTreeContextMenu: function() {
    var self = this;
    var treeNodeAction = function(key) {
        var nodes = zTree.getSelectedNodes();
        if (nodes.length == 0) {
            alert("请先选择一个节点");
            return;
        };
        treeNode = nodes[0];

        if (key == 'rname') {
            zTree.editName(treeNode);
        } else if (key == "info") {
            self.editFoler();
        } else if (key == "delete" || key == "remove") {
            if (treeNode.children && treeNode.children.length > 0) {
                art.dialog({
                    title: '消息',
                    content: '当前节点还有子节点,无法执行删除操作。请先删除子节点',
                    ok: function() {
                        return true;
                    }
                });
                return;
            }
            if (_UserInfo.username != "sys") {
                art.dialog({
                    title: '消息',
                    content: '当前用户无删除目录权限',
                    ok: function() {
                        return true;
                    }
                });
                return;
            }
            var dialog = art.dialog({
                title: '警告!',
                content: '确定要删除吗?',
                ok: function() {
                    var delRecord = ds_metamodel.getRecordByKey(treeNode.id);
                    if (delRecord) {
                        ds_metamodel.remove(delRecord);
                        ds_metamodel.commit();
                    };
                    zTree.removeNode(treeNode);
                    return true;
                },
                cancel: function() {
                    return true;
                }
            });
        } else if (key == "pickobjadd") {
            function afterSelect(rs) {
              var arrayTopic=[];
                for (var i = 0; i < rs.length; i++) {
                    var r = rs[i];
                    
                    arrayTopic.push(r.get('XMLID'));
                };
                ai.executeSQL("update metaobj set TOPICCODE='"+treeNode.id+"' where xmlid in('"+arrayTopic.join("','")+"')"); 
             
                 $("#"+treeNode.tId+"_a").click();
            };
            var selSql = "select objname VALUES1,objcnname VALUES2,REMARK ,xmlid  from metaobj" + " where topiccode<>'" + treeNode.id + "'";
            var selBox = new SelectBox({
                sql: selSql,
                callback: afterSelect
            });
            selBox.show();
        };
    };
    ///树的绑定
    $.contextMenu({
        zIndex: 9999,
        selector: ".curSelectedNode",
        className: ".menufolder",
        callback: function(key, options) {
            treeNodeAction(key);
        },
        items: {
            "rname": {
                name: '重命名',
                className: "rname",
                icon: "pencil",
                accesskey: "r"
            },
            "remove": {
                name: '删除',
                className: "remove",
                icon: "trash",
                accesskey: "d"
            },

            "sep1": "--------",
            "copy": {
                name: "复制",
                className: "copy",
                icon: "copy",
                accesskey: "c"
            },
            "cute": {
                name: "剪切",
                className: "cute",
                icon: "cut",
                accesskey: "k"
            },

            "sep2": "--------",
            "search": {
                name: "文件夹中搜索",
                className: "search",
                icon: "search",
                accesskey: "s"
            },
            "pickobjadd": {
                name: "选择对象到此",
                className: "search",
                icon: "search",
                accesskey: "p"
            },
            "fav": {
                name: "添加到收藏夹",
                className: "fav",
                icon: "star",
                accesskey: "f"
            },

            "sep3": "--------",
            "info": {
                name: "属性",
                className: "info",
                icon: "info",
                accesskey: "i"
            }
        }
    });
    $("html").bind("click", function() {
      $('.context-menu-list').filter(':visible').trigger('contextmenu:hide');
    });
  },
  pickObjAddTo:function(){
    function afterSelect(rs) {
      var arrayTopic=[];
        for (var i = 0; i < rs.length; i++) {
            var r = rs[i];
            
            arrayTopic.push(r.get('XMLID'));
        };
        ai.executeSQL("update metaobj set TOPICCODE='"+treeNode.id+"' where xmlid in('"+arrayTopic.join("','")+"')"); 
     
         $("#"+treeNode.tId+"_a").click();
    };
    var selSql = "select objname VALUES1,objcnname VALUES2,REMARK ,xmlid  from metaobj" + " where topiccode<>'" + treeNode.id + "'";
    var selBox = new SelectBox({
        sql: selSql,
        callback: afterSelect
    });
    selBox.show();
  },
  editFoler: function() { //修改文件夹
    afterOK = function(fieldVals) {
      if (zTree.getSelectedNodes().length == 0) return false;
      var node = zTree.getSelectedNodes()[0];
      var newRecord = ds_metamodel.getRecordByKey(node.id);
      if (!newRecord) return;

      newRecord.set('MODELNAME', fieldVals['MODELNAME']);
      newRecord.set('MODELTYPE', fieldVals['MODELTYPE']);
      newRecord.set('STATE', "on");
      ds_metamodel.commit();
      node.name = fieldVals['MODELNAME'];
      zTree.updateNode(node);
    }
    beforeOK = function(fieldVals) {
        for (key in fieldVals) {
            //if(!fieldVals[key]){alert(key+"值不允许为空");return false;}
        };
    }
    if (zTree.getSelectedNodes().length == 0) return false;
    var node = zTree.getSelectedNodes()[0];
    var formcfg = ({
      title: '编辑文件夹',
      fieldChange: function(fieldName, newVal) {
      },
      items: [
        // {type:'text',label:'编号',notNull:true,fieldName:'MODELCODE',value:node.id,disabled:true},
        {
            type: 'text',
            label: '名称',
            notNull: true,
            fieldName: 'MODELNAME',
            value: node.name
        },
        {
            type: 'combox',
            label: '类型',
            fieldName: 'MODELTYPE',
            storesql: Main.getObjType(),
            value: node.objtype
        },
        {
            type: 'checkbox',
            label: '权限类型',
            fieldName: 'RIGHT_TYPE',
            storesql: '公有,私有',
            width: 220,
            value: "公有"
        },
        {
            type: 'text',
            label: '管理者',
            fieldName: 'OWNER',
            width: 220,
            value: "sys"
        },
        {
            type: 'text',
            label: '数据内容',
            fieldName: 'REMARK',
            width: 220,
            value: ""
        }
      // ,{type:'combox',label:'边框',fieldName:'border',width:120,storesql:'none,1px,2px,3px,4px',value:"none"},
      ]
    });
    showDialogForm(formcfg, afterOK, beforeOK);
  },
  gotoPath:function(targetCode){
    if(!targetCode) return;
    var node = this.zTree.getNodeByParam("id",targetCode);
    if(!node) return;
    if(node.getParentNode()) this.zTree.expandNode(node.getParentNode());
    if(node) $("#"+node.tId+"_a").click();
  }
});
/*PaaS的树开发*/
AI.TreeIndex.PaaS =AI.TreeIndex.$extend({ 
  teamcode:'',teaname:'',category: 'topic', myOptions: null, myTree:null, firstLoad: true,
  initTree:function(options){
    if(this.firstLoad) {
      $("div.frame-left").on('click','#catchanger',this.catchange);
      // $("#catchanger").show();
      // $("ul.nav").after('<i style="float:right;top:7px;z-index:999" id="catchanger" class="btn glyphicon glyphicon-refresh"></i>');
      this.firstLoad = false;
    }
    this.myOptions = options;
    myTree = this;
    if(this.zTree) this.zTree.destroy();
    this.menuData=[];
    this.buildTreeMenu(this.menuData,options);    
    this.buildTreeContextMenu();
    $.fn.zTree.init($("#folderList"), this.setting, this.menuData);
    this.zTree = $.fn.zTree.getZTreeObj("folderList");
  },
  showErrorInfo:function(title,remark,type){
    $(".frame-main").hide();
    $(".tipinfo .title").html(title);
    $(".tipinfo .content").html(remark);
    $(".tipinfo").show();
  },
  catchange:function() {
    myTree.category == 'database' ? myTree.category = 'topic' : myTree.category = 'database';
    myTree.initTree(myTree.myOptions);
    return false;
  },
  buildPaasTeamTitle:function(){
    var userTeamData = ai.getStoreData("select distinct a.team_code,team_name,'' role_code from meta_team a,meta_team_role_user b where a.team_code=b.team_code and username='"+_UserInfo.username+"'");
    if(userTeamData.length==0){
      this.showErrorInfo("报错了",'您还没有加入任何团队,请先申请团队进行加入','max');
      return false;
    }
    $('#treetitle').html('<span class="title">团队:信息</span> <span class="caret"></span>');
    if(userTeamData.length>1){
      $('#treetitle').popover({
        title:"您参加多个团队,",
        container:'body',
        animation:true,
        html:true,
        delay: { "show": 300, "hide": 500 },
        content:'选择这里进行切换',
        placement:'bottom',
        trigger:"manual"
      }).popover('show').popover('toggle') ;
    }
    var html="";
    for(var i=0;i<userTeamData.length;i++){
      var team =userTeamData[i];
      if(_.isUndefined(this.teamcode)||!this.teamcode ) {
        _UserInfo.teamCode = this.teamcode=team.TEAM_CODE;
        _UserInfo.teamName = this.teamName=team.TEAM_NAME;
        _UserInfo.teamRoles = [{roleCode:team.ROLE_CODE}];
        $("#treetitle .title").html(this.teamName);
      }
      else if(this.teamcode == team.TEAM_CODE){
        // _UserInfo.teamRoles.push({roleCode:team.ROLE_CODE});
        $("#treetitle .title").html(team.TEAM_NAME).attr("curteam",team.TEAM_CODE);
      }
      html+='<li><a id="'+team.TEAM_CODE+'" href="#">'+team.TEAM_NAME+'</a></li>';
    }
    html+='<li role="separator" class="divider"></li>';
    // html+='<li><a href="#">团队管理</a></li>';
    // html+='<li><a href="#">Pass平台管理</a></li>';
    var self=this;
    $("#teammenu").empty().append(html);
    $("#teammenu li a").click(function(){
      $("#treetitle .title").html($(this).html()).attr("curteam",$(this).attr("id"));
      self.initTree({teamcode:$(this).attr("id")})
    });
  },
  buildDevMgrMenu:function(data){
    var self=this;
    function getChildNodes(pNode){
      if(!pNode) return;
      for(var i=0;i<teamTopicStroe.getCount();i++){
        var r=teamTopicStroe.getAt(i);
        if(r.get("PARENTCODE")!=pNode.rulecode) continue;
        var ruletype = r.get('RULETYPE');
        var nodeId = r.get('TOPICNAME');
        var rulename=r.get('RULENAME');
        var objtype=r.get('RULETYPE').toUpperCase();
        if(ruletype=='database') nodeId =  r.get('DBNAME');
        var fieldname=objtype.toLowerCase();
        if(fieldname=='topic') fieldname='topiccode';
        if(fieldname=='database') fieldname='dbname';
        var node={title:rulename,id:nodeId,name:rulename,fieldname:fieldname,objtype:objtype,isParent:false,rulecode:r.get('RULE_CODE'),children:[]};

        pNode.children.push(node);
        pNode.isParent=true; 
        getChildNodes(node);
      }
    }

    function getDatabaseChildNodes(pNode) {
      console.log(pNode);
      var dbname = pNode.id;
      var dbcnname = pNode.name;

      var typeArr = [];
      var sql = "select * from metaobj_property where xmlid = '" + dbname + "' and pro_key = 'refmodel'";
      var data = ai.getStoreData(sql);
      if(!data) return;
      typeArr = data[0].PRO_VALUE.split(",");

      for(var i=0; i<typeArr.length; i++) {
        var objtype = typeArr[i];
        var objname = ai.getStoreData("SELECT * FROM metaobjmodel WHERE objtype = '" + objtype + "'")[0].OBJNAME;
        var node = {title: objname,id: objtype,name: objname, dbname: dbname, objtype: objtype, fieldname: 'objtype'};
        pNode.children.push(node);
      }
    }

    var teamdbsql ="SELECT dbname,topicname,rule_code,parentcode,ruletype,rulename,ruletext FROM meta_team_permission where team_code='{team_code}' and ruletype in('database','topic') order by rule_code";
    var devNode={title:'开发管理',id:'R01',name:'开发管理',objtype:'folder', children: []};
    var teamTopicStroe = new AI.JsonStore({///数据库列表
      sql : teamdbsql.replace("{team_code}",this.teamcode),
      pageSize:-1
    });
    for(var i=0;i<teamTopicStroe.getCount();i++){
      var r=teamTopicStroe.getAt(i);
      if(r.get('PARENTCODE')!=devNode.id) continue;
      var ruletype = r.get('RULETYPE');
      var nodeId = r.get('TOPICNAME');
      var objtype=r.get('RULETYPE').toUpperCase();
      var rulename=r.get('RULENAME');
      if(ruletype=='database') nodeId =  r.get('DBNAME');
      var fieldname=objtype.toLowerCase();
      if(fieldname=='topic') fieldname='topiccode';
      if(fieldname=='database') fieldname='dbname';
      var node={title:rulename,id:nodeId,name:rulename,fieldname:fieldname,objtype:objtype,isParent:false,rulecode:r.get('RULE_CODE'),children:[]};
      if(this.category == 'topic') {
        getChildNodes(node);
      } else if(this.category == 'database') {
        getDatabaseChildNodes(node);
      }
      devNode.children.push(node);  
    };
    data.push(devNode);
  },
  transZTreeDataToJson:function(datas, id, pid, children){    
      var r = [], hash = {}, i = 0, j = 0, len = datas.length;    
      for(; i < len; i++){    
          hash[datas[i][id]] = datas[i];    
      }    
      for(; j < len; j++){    
          var aVal = datas[j], hashVP = hash[aVal[pid]]; 
          var objtype=aVal.RULETYPE.toUpperCase();
          var rulename=aVal.RULENAME;
          var nodeId = aVal.TOPICNAME;
          var ruletype = aVal.RULETYPE;
          if(ruletype=='database') nodeId =  aVal.DBNAME;
          var fieldname=objtype.toLowerCase();
          if(fieldname=='topic') fieldname='topiccode';
          if(fieldname=='database') fieldname='dbname';
          aVal.title = aVal.RULENAME;
          aVal.name = aVal.RULENAME;
          aVal.fieldname = fieldname;
          aVal.objtype = objtype;
          aVal.rulecode = aVal.RULE_CODE;
          aVal.id = nodeId;          
          if(hashVP){    
              !hashVP[children] && (hashVP[children] = []);    
              hashVP[children].push(aVal);    
          }else{    
              r.push(aVal);    
          }    
      }    
      return r;    
  },
  buildPaaSDevMgrMenu:function(data){
	    var self=this;
	    var teamdbsql ="SELECT dbname,topicname,rule_code,parentcode,ruletype,rulename,ruletext FROM meta_team_permission where team_code='{team_code}' and ruletype in('database','topic') order by rule_code";
	    var devNode={title:'开发管理',id:'R01',name:'开发管理',objtype:'folder', children: []};
	    var teamTopicStroe = new AI.JsonStore({///数据库列表
	      sql : teamdbsql.replace("{team_code}",this.teamcode),
	      pageSize:-1
	    });
	    devNode.children = self.transZTreeDataToJson(teamTopicStroe.root,"RULE_CODE","PARENTCODE","children");
	    data.push(devNode);
  },
  treeNodeClick:function(event,treeId,treeNode) {

    function getChildNodes(pNode){
      if(!pNode) return;
      var children = [];
      for(var i=0;i<teamTopicStroe.getCount();i++){
        var r=teamTopicStroe.getAt(i);
        if(r.get("PARENTCODE")!=pNode.rulecode) continue;
        var ruletype = r.get('RULETYPE');
          var nodeId = r.get('TOPICNAME');
          var rulename=r.get('RULENAME');
          var objtype=r.get('RULETYPE').toUpperCase();
          if(ruletype=='database') nodeId =  r.get('DBNAME');
          var fieldname=objtype.toLowerCase();
          if(fieldname=='topic') fieldname='topiccode';
          if(fieldname=='database') fieldname='dbname';
           var node={title:rulename,id:nodeId,name:rulename,fieldname:fieldname,objtype:objtype,isParent:false,rulecode:r.get('RULE_CODE'),children:[]};

         children.push(node);
         pNode.isParent=true; 
          // getChildNodes(node);
      };
      return children;
    }

    function getDatabaseChildNodes(pNode) {
      if(!pNode) return;
      var children = [];

      var dbname = pNode.id;
      var dbcnname = pNode.name;

      var typeArr = [];
      var sql = "select * from metaobj_property where xmlid = '" + dbname + "' and pro_key = 'refmodel'";
      var data = ai.getStoreData(sql);
      if(!data) return;
      typeArr = data[0].PRO_VALUE.split(",");

      for(var i=0; i<typeArr.length; i++) {
        var objtype = typeArr[i];
        var objname = ai.getStoreData("SELECT * FROM metaobjmodel WHERE objtype = '" + objtype + "'")[0].OBJNAME;
        var node = {title: objname,id: objtype,name: objname, dbname: dbname, objtype: objtype, fieldname: 'objtype'};
        children.push(node);
      }
      return children;
    }

    function getDevNodes(devPnode) {
      for(var i=0;i<teamTopicStroe.getCount();i++){
        var r=teamTopicStroe.getAt(i);
        if(r.get('PARENTCODE')!=devPnode.id) continue;
        var ruletype = r.get('RULETYPE');
        var nodeId = r.get('TOPICNAME');
        var objtype=r.get('RULETYPE').toUpperCase();
        var rulename=r.get('RULENAME');
        if(ruletype=='database') nodeId =  r.get('DBNAME');
        var fieldname=objtype.toLowerCase();
        if(fieldname=='topic') fieldname='topiccode';
        if(fieldname=='database') fieldname='dbname';

        var node={title:rulename,id:nodeId,name:rulename,fieldname:fieldname,objtype:objtype,isParent:false,rulecode:r.get('RULE_CODE'),children:[]};
        children.push(node);  
      };
      return children;
    }

    var teamcode = this.teamcode||'T001';
    var children = [];
    var teamdbsql ="SELECT dbname,topicname,rule_code,parentcode,ruletype,rulename,ruletext FROM meta_team_permission where team_code='{team_code}' and ruletype in('database','topic') order by rule_code";
    var teamTopicStroe = new AI.JsonStore({///数据库列表
      sql : teamdbsql.replace("{team_code}",teamcode),
      pageSize:-1
    });

    if(!treeNode.children||treeNode.children.length ==0){
      var children = [];
      var id = treeNode.id;
      if(treeNode.id == 'R01'){
        children = getDevNodes(treeNode);
        treeNode.isParent = true;
      } else if (!!treeNode.rulecode && treeNode.rulecode.indexOf('R01') != -1) {
        if(this.category == 'topic') {
          children = getChildNodes(treeNode);
        } else if(this.category == 'database') {
          children = getDatabaseChildNodes(treeNode);
        }
      }
      if(!!children && children.length>0) this.zTree.addNodes(treeNode, children);
    }
    else{
      this.zTree.expandNode(treeNode);
    }
    this.zTree.selectNode(treeNode);
    $("#folderList li a span").attr('data-toggle','tooltip').attr('data-placement','right');
    $("[data-toggle='tooltip']").tooltip();
    // console.log(treeNode);
    //var r = ds_metamodel.getRecordByKey(treeNode.id);
    var menuItemData = MainFram.treeIndex.getMenuItemData(treeNode.id);
    if(menuItemData && menuItemData.url && menuItemData.url.length>5){
      $("#frame-right-main").hide();
      var _url= menuItemData.url;
      if(_url.indexOf("http://")>=0) _url = menuItemData.url
      else _url="/"+contextPath+"/"+menuItemData.url;
        
      var result = MainFram.explore.getTreeWhere(treeNode);
      if(_url.indexOf("?")!=-1){
        _url =_url+"&result="+result;
      }
      _url=_url.replace('{contextPath}',contextPath);
      _url = this.dealUrl(_url,{TEAMCODE:this.teamcode||''});
      if(_url&&_url.indexOf("opener=tabsheet")!=-1){
//    	  $("#frame-right-main").show();
    	  ai.addTabSheet(treeNode.id,menuItemData.name,_url,true); 
      }
      else{
    	  $("#frame-right-iframe").attr("src",_url).show();
      }
    }
    else  {
      $("#frame-right-iframe").attr("src","").hide();
      $("#frame-right-main").show();
    MainFram.explore.gotoPath(treeNode,menuItemData);
    }
  },
  buildAsyncMenu:function(rootCode,data) {
    var self=this;
    var teamdbsql ="SELECT dbname,topicname,rule_code,parentcode,ruletype,rulename,ruletext FROM meta_team_permission where team_code='{team_code}' and ruletype in('database','topic') order by rule_code";
    var devNode={title:'开发管理',id:'R01',name:'开发管理',objtype:'folder', children: [],isParent: false};
    data.push(devNode);
    this.loadModelTreeData(rootCode,data,false);
  },
  buildTreeMenu:function(menuData,options){///按PaaS团队加载
    this.teamcode=options.teamcode||'';
    this.rootcode=options.rootCode||'paas';
    var loadMethod = options.loadMethod||'sync';
    // this.buildDataMgrMenu(menuData);
    if(this.buildPaasTeamTitle()==false) {return};
    if(loadMethod == 'async'){
      this.buildAsyncMenu(this.rootcode,menuData);
    }
    else{
      this.buildPaaSDevMgrMenu(menuData);
      this.loadModelTreeData(this.rootcode,menuData,false);
    }
  }
});
/*DataIndex的树开发*/
AI.TreeIndex.DataIndex =AI.TreeIndex.$extend({
  loadTreeData: function(options) {
    options = options||{};
    this.menuData=[];
    var containerId=options.containerId||"folderList";
    $("#treetitle .title").html('<span class="glyphicon glyphicon-list"></span>数据目录');
    // $("#teammenu").append('<li><a id="report" href="#"><span class="glyphicon glyphicon-eye-open"></span>统计分析</a></li>');
    // $("#teammenu").append('<li><a id="manager" href="#"><span class="glyphicon glyphicon-eye-open"></span>目录管理</a></li>');
    var loadMethod = options.loadMethod||'sync';
    var targetCode = options.targetCode||null;
    var nodes = [];
    if(loadMethod == 'async'){
      nodes = this.getDatabase();
    }
    else{
      nodes = this.buildDataIndex();
    }
    $.fn.zTree.init($("#"+containerId), this.setting,nodes);
    this.zTree = $.fn.zTree.getZTreeObj(containerId);
    this.gotoPath(targetCode);
  },
  getDatabase:function(){
    var data = [];
    var dbArray=ai.getStoreData("select dbname,cnname from metadb_list order by ordseq");
    for(var i=0;i<dbArray.length;i++){
      var db=dbArray[i];
      var objtype = 'TAB';
      var node={title:db.CNNAME,id:db.DBNAME,name:db.CNNAME,dbname:db.DBNAME,url:"ftl/catalog/dataindex/ai.data.index?objtype="+objtype+"&topiccode=&dbname="+db.DBNAME,fieldname:'dbname',objtype:objtype,children:[]};
      // addDBStructParent(node.id,"",node.children);
      data.push(node);
    }
    return data;
  },
  getDbStruct:function(dbname,parentCode){
    var data = [];
    var sql = "select DBNAME,RULECODE,PARENTCODE,RULETYPE,RULENAME,FUNC_ID from metadb_struct where  dbname ='"+dbname+"' "
        +(!parentCode?" and (parentCode is null or parentCode = '')":" and parentcode = '"+parentCode+"'")+" order by DBNAME,RULECODE" ;
    var dbTopicStore= new AI.JsonStore({
      sql: sql,
      key: "RULECODE",
      pageSize: -1,
      table: "PARENTCODE"
    });
    for(var i=0;i<dbTopicStore.getCount();i++){
        var r=dbTopicStore.getAt(i);
        var objtype=r.get("FUNC_ID")||"";
        if(objtype) objtype=objtype.split(",")[0];
        objtype='TAB';
        var node={title:r.get("RULENAME"),id:r.get("RULECODE"),name:r.get("RULENAME"),dbname:dbname,url:"ftl/catalog/dataindex/ai.data.index?objtype="+objtype+"&topiccode="+r.get("RULECODE")+"&dbname="+r.get("DBNAME"),fieldname:r.get('RULETYPE'),objtype:'TOPIC', isParent:false,children:[]};
        data.push(node);  
    }
    return data;
  },
  treeNodeClick:function(event,treeId,treeNode){
    if(!treeNode.children||treeNode.children.length ==0){
      var children = [];
      var id = treeNode.id;
      if(treeNode.dbname== treeNode.id){
        id = null;
      }
      children = this.getDbStruct(treeNode.dbname,id);
      if(children.length>0) this.zTree.addNodes(treeNode, children);
    }
    else{
      this.zTree.expandNode(treeNode);
    }
    this.zTree.selectNode(treeNode);

    $("#folderList li a span").attr('data-toggle','tooltip').attr('data-placement','right');
    $("[data-toggle='tooltip']").tooltip();
    // console.log(treeNode);
    //var r = ds_metamodel.getRecordByKey(treeNode.id);
    // var menuItemData = MainFram.treeIndex.getMenuItemData(treeNode.id);
    var menuItemData = treeNode;
    if(menuItemData && menuItemData.url && menuItemData.url.length>5){
      $("#frame-right-main").hide();
      var _url= menuItemData.url;
      if(_url.indexOf("http://")>=0) _url = menuItemData.url
      else _url="/"+contextPath+"/"+menuItemData.url;
        
      var result = MainFram.explore.getTreeWhere(treeNode);
      if(_url.indexOf("?")!=-1){
        _url =_url+"&result="+result;
      }
      _url=_url.replace('{contextPath}',contextPath);
      _url = this.dealUrl(_url,{TEAMCODE:this.teamcode||''});
      if(_url&&_url.indexOf("opener=tabsheet")!=-1){
    	  ai.addTabSheet(treeNode.id,menuItemData.name,_url,true); 
      }
      else{
    	  $("#frame-right-iframe").attr("src",_url).show();
      }
//      $("#frame-right-iframe").attr("src",_url).show();
    }
    else {
      $("#frame-right-iframe").attr("src","").hide();
      $("#frame-right-main").show();
      MainFram.explore.gotoPath(treeNode,menuItemData);
    }
  },
  buildDataIndex:function(){
    var data = [];
    function getChildNodes(dbname,pNode){
      for(var i=0;i<dbTopicStore.getCount();i++){
          var r=dbTopicStore.getAt(i);
          if(r.get("DBNAME")!=dbname) continue;
          if(r.get("PARENTCODE")!=pNode.id) continue;
          var objtype='TAB';
          var node={title:r.get("RULENAME"),id:r.get("RULECODE"),name:r.get("RULENAME"),dbname:pNode.dbname,url:"ftl/catalog/dataindex/ai.data.index?objtype="+objtype+"&topiccode="+r.get("RULECODE")+"&dbname="+r.get("DBNAME"),fieldname:r.get('RULETYPE'),objtype:'TOPIC', isParent:false,children:[]};
           pNode.children.push(node); pNode.isParent=true;
          getChildNodes(dbname,node);
        };
    };
    addDBStructParent=function(dbname,rootCode,dbdata){
      for(var i=0;i<dbTopicStore.getCount();i++){
        var r=dbTopicStore.getAt(i);
        if(r.get("DBNAME")!=dbname) continue;
        if(!r.get('PARENTCODE')) r.set('PARENTCODE','');
        if(!rootCode) rootCode="";
        if(r.get('PARENTCODE')!=rootCode) continue;
        var objtype='TAB';
        var node={title:r.get("RULENAME"),id:r.get("RULECODE"),name:r.get("RULENAME"),objtype:"TAB",url:"ftl/catalog/dataindex/ai.data.index?objtype="+objtype+"&topiccode="+r.get("RULECODE")+"&dbname="+r.get("DBNAME"),fieldname:dbname,isParent:false,children:[]};
        getChildNodes(dbname,node);
        dbdata.push(node);  
       }
    }
    // var dbArray=ai.getStoreData("select dbname,cnname from metadb_list  order by ordseq");
    var dbTopicStore= new AI.JsonStore({
      sql: "select DBNAME,RULECODE,PARENTCODE,RULETYPE,RULENAME,FUNC_ID from metadb_struct where  dbname in(select dbname from metadb_list) order by DBNAME,RULECODE" ,
      key: "RULECODE",
      pageSize: -1,
      table: "PARENTCODE"
    });
    var dbArray=ai.getStoreData("select dbname,cnname from metadb_list order by ordseq");
    for(var i=0;i<dbArray.length;i++){
      var db=dbArray[i];
      var node={title:db.CNNAME,id:db.DBNAME,name:db.CNNAME,dbname:db.DBNAME,fieldname:'dbname',objtype:'TAB',url:"ftl/catalog/dataindex/ai.data.index?objtype=TAB&dbname="+db.DBNAME,children:[]};
      addDBStructParent(node.id,"",node.children);
      data.push(node);
    }
    return data;
  }
});
/*MetaIndex的树开发*/
AI.TreeIndex.MetaIndex =AI.TreeIndex.$extend({
  loadTreeData: function(options) {
    options = options||{};
    var loadMethod = options.loadMethod||'sync';
    var targetCode = options.targetCode||null;
    this.menuData=[];
    var containerId=options.containerId||"folderList";
    this.addMetaModelMenu(this.menuData);
    // this.addTaskMgrMenu(this.menuData)
    // this.addSimpleStateMenu(this.menuData); 
    
    $.fn.zTree.init($("#"+containerId), this.setting, this.menuData);
    this.zTree = $.fn.zTree.getZTreeObj(containerId);
    this.gotoPath(targetCode);
  },
  addMetaModelMenu:function(data){///按元模型加载
    function getChildNodes(pNode) {
      for (var i = 0; i < ds_metamodel.getCount(); i++) {
          var r = ds_metamodel.getAt(i);
          if (r.get('PARENTCODE') != pNode.id) continue;
          pNode.isParent = true;
          var node = {
              title:r.get('OBJNAME'),
              id: r.get('OBJCODE'),
              name: r.get('OBJNAME'),
              objtype: r.get('OBJTYPE'),
              filter:"OBJTYPE='{objtype}'",
              isParent: false,
              children: []
          };
          pNode.children.push(node);
          getChildNodes(node);
      };
    };
    
    var metamodelSql = "select OBJCODE,OBJTYPE,PARENTCODE,OBJNAME from metaobjmodel order by ORDSEQ  ";
    ds_metamodel = new AI.JsonStore({
        sql: metamodelSql ,
        key: "OBJCODE",
        pageSize: -1,
        table: "METAMODEL"
    });
    for (var i = 0; i < ds_metamodel.getCount(); i++) {
        var r = ds_metamodel.getAt(i);
        
        if (r.get('PARENTCODE') !='META' ) continue;
      
        var node = {
            title:r.get('OBJNAME'),
            id: r.get('OBJCODE'),
            name: r.get('OBJNAME'), 
            fieldname:"OBJTYPE",
            objtype: r.get('OBJTYPE'),
            isParent: false,
            children: []
        };
        data.push(node);
        getChildNodes(node);
    };
  }
});
/*DevIndex的树开发*/
AI.TreeIndex.DevIndex =AI.TreeIndex.$extend({
  loadTreeData: function(options) {
    options = options||{};
    var loadMethod = options.loadMethod||'sync';
    var targetCode = options.targetCode||null;
    this.menuData=[];
    var containerId=options.containerId||"folderList";

    if(loadMethod == 'async'){
      var dbArray=ai.getStoreData("select dbname,cnname from metadbcfg where DBUSEGE <> 1 OR DBUSEGE IS NULL order by dbname");
      for(var i=0;i<dbArray.length;i++){
        var db=dbArray[i];
        var node={title:db.CNNAME,id:db.DBNAME,name:db.CNNAME,dbname:db.DBNAME,fieldname:'dbname',objtype:'DATABASE',children:[]};
        this.menuData.push(node);
      }
    }
    else{
      this.buildDevIndex(this.menuData);
    }
    
    $.fn.zTree.init($("#"+containerId), this.setting, this.menuData);
    this.zTree = $.fn.zTree.getZTreeObj(containerId);
    this.gotoPath(targetCode);
  },
  buildDevIndex:function(data){
    $("#treetitle .title").html('<span class="glyphicon glyphicon-list"></span>数据目录');
    function getChildNodes(dbname,pNode){
      for(var i=0;i<dbTopicStore.getCount();i++){
          var r=dbTopicStore.getAt(i);
          if(r.get("DBNAME")!=dbname) continue;
          if(r.get("PARENTCODE")!=pNode.id) continue;
          var objtype=r.get("FUNC_ID")||"";
          if(objtype) objtype=objtype.split(",")[0];
          var node={title:r.get("RULENAME"),id:r.get("RULECODE"),name:r.get("RULENAME"),dbname:pNode.dbname,fieldname:'topiccode',objtype:'TOPIC', isParent:false,children:[]};
           pNode.children.push(node); pNode.isParent=true;
          getChildNodes(dbname,node);
        };
    };
    addDBStructParent=function(dbname,rootCode,dbdata){
      for(var i=0;i<dbTopicStore.getCount();i++){
        var r=dbTopicStore.getAt(i);
        if(r.get("DBNAME")!=dbname) continue;
        if(!r.get('PARENTCODE')) r.set('PARENTCODE','');
        if(!rootCode) rootCode="";
        if(r.get('PARENTCODE')!=rootCode) continue;
        var objtype=r.get("FUNC_ID")||"";
        if(objtype) objtype=objtype.split(",")[0];
        var node={title:r.get("RULENAME"),id:r.get("RULECODE"),name:r.get("RULENAME"),objtype:"TOPIC",fieldname:'topiccode',isParent:false,children:[]};
        getChildNodes(dbname,node);
        dbdata.push(node);  
       }
    }
    var dbTopicStore= new AI.JsonStore({
      sql: "select DBNAME,RULECODE,PARENTCODE,RULETYPE,RULENAME,FUNC_ID from metadb_struct where  dbname in(select dbname from metadbcfg) order by DBNAME,RULECODE" ,
      key: "RULECODE",
      pageSize: -1,
      table: "PARENTCODE"
    });
    var dbArray=ai.getStoreData("select dbname,cnname from metadbcfg where DBUSEGE <> 1 OR DBUSEGE IS NULL order by dbname");
    for(var i=0;i<dbArray.length;i++){
      var db=dbArray[i];
      var node={title:db.CNNAME,id:db.DBNAME,name:db.CNNAME,dbname:db.DBNAME,fieldname:'dbname',objtype:'DATABASE',children:[]};
      addDBStructParent(node.id,"",node.children);
        data.push(node);
    }
  },
  getDbStruct:function(dbname,parentCode){
    var data = [];
    var sql = "select DBNAME,RULECODE,PARENTCODE,RULETYPE,RULENAME,FUNC_ID from metadb_struct where  dbname ='"+dbname+"' "
        +(!parentCode?" and (parentCode is null or parentCode = '')":" and parentcode = '"+parentCode+"'")+" order by DBNAME,RULECODE" ;
    var dbTopicStore= new AI.JsonStore({
      sql: sql,
      key: "RULECODE",
      pageSize: -1,
      table: "PARENTCODE"
    });
    for(var i=0;i<dbTopicStore.getCount();i++){
        var r=dbTopicStore.getAt(i);
        var objtype=r.get("FUNC_ID")||"";
        if(objtype) objtype=objtype.split(",")[0];
        var node={title:r.get("RULENAME"),id:r.get("RULECODE"),name:r.get("RULENAME"),dbname:dbname,url:"ftl/catalog/dataindex/ai.data.index?objtype="+objtype+"&topiccode="+r.get("RULECODE")+"&dbname="+r.get("DBNAME"),fieldname:r.get('RULETYPE'),objtype:'TOPIC', isParent:false,children:[]};
        data.push(node);  
    }
    return data;
  },
  treeNodeClick:function(event,treeId,treeNode){
    if(!treeNode.children||treeNode.children.length ==0){
      var children = [];
      var id = treeNode.id;
      if(treeNode.dbname== treeNode.id){
        id = null;
      }
      children = this.getDbStruct(treeNode.dbname,id);
      if(children.length>0) this.zTree.addNodes(treeNode, children);
    }
    else{
      this.zTree.expandNode(treeNode);
    }
    this.zTree.selectNode(treeNode);

    $("#folderList li a span").attr('data-toggle','tooltip').attr('data-placement','right');
    $("[data-toggle='tooltip']").tooltip();
    // console.log(treeNode);
    //var r = ds_metamodel.getRecordByKey(treeNode.id);
    // var menuItemData = MainFram.treeIndex.getMenuItemData(treeNode.id);
    var menuItemData = treeNode;
    if(menuItemData && menuItemData.url && menuItemData.url.length>5){
      $("#frame-right-main").hide();
      var _url= menuItemData.url;
      if(_url.indexOf("http://")>=0) _url = menuItemData.url
      else _url="/"+contextPath+"/"+menuItemData.url;
        
      var result = MainFram.explore.getTreeWhere(treeNode);
      if(_url.indexOf("?")!=-1){
        _url =_url+"&result="+result;
      }
      _url=_url.replace('{contextPath}',contextPath);
      _url = this.dealUrl(_url,{TEAMCODE:this.teamcode||''});
      $("#frame-right-iframe").attr("src",_url).show();
    }
    else {
      $("#frame-right-iframe").attr("src","").hide();
      $("#frame-right-main").show();
      MainFram.explore.gotoPath(treeNode,menuItemData);
    }
  }
});